package com.example.controller;

import com.example.controller.utils.SMSService;
import com.example.domain.Option;
import com.example.domain.Question;
import com.example.domain.Questionnaire;
import com.example.domain.User;
import com.example.service.*;
import net.minidev.json.JSONArray;
import net.minidev.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;


import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


@Controller
@RequestMapping("/client")
public class UserController {

    @Autowired
    UserService userService;

    @Autowired
    QuestionnaireService questionnaireService;

    @Autowired
    QuestionService questionService;

    @Autowired
    OptionService optionService;
    @Autowired
    AnswerService answerService;

    @Autowired
    SMSService service;

    HttpSession session;

    static int questionId=1;

    static int optionId=1;

    //发送验证码
//    @PostMapping("/sendMessage")
//    public String send(@RequestParam("phone_num")String phoneNum) throws Exception {
//
//        service.sendMessage(phoneNum,"9723");
//        return "redirect:/client/register";
//    }

    //用户登录页面，使用post请求
    @PostMapping("/login")
    public String login(@RequestParam("username")String username, @RequestParam("password")String password, HttpServletRequest request, HttpServletResponse response){
        boolean result=userService.login(username,password);
        session = request.getSession();
//
//        session.setAttribute("user",userService.findByUsername(username));
        if(result) {
            Cookie cookie = new Cookie("isLogin","success");
            cookie.setMaxAge(60*60*24);
            cookie.setPath("/");
            response.addCookie(cookie);
            session.setAttribute("isLogin", username);
            session.setAttribute("username", username);
            session.setAttribute("user",userService.findByUsername(username));
            return "redirect:/client/home";
        }
        else {
            request.setAttribute("message","账号或密码错误，请重新输入");
            return "UserLogin";
        }
    }

    //用户注册界面，使用post请求
    @PostMapping("/register")
    public String register(@RequestParam("username")String username,
                           @RequestParam("phone_num")String phoneNum,
                           @RequestParam("password")String password,HttpServletRequest request){
        User user1 = userService.findByUsername(username);
        if (Objects.equals(username, "")) {
            request.setAttribute("message", "用户名为空，请重新输入");
        } else if (user1 != null) {
            request.setAttribute("message", "用户名已存在，请重新输入");
        } else if (Objects.equals(phoneNum, "")) {
            request.setAttribute("message", "电话为空，请重新输入");
        } else if (Objects.equals(password, "")) {
            request.setAttribute("message", "密码为空，请重新输入");
        } else {
            User user = new User(username, password, phoneNum, "icon");
            boolean result = userService.register(user);
            if (result) {
                return "redirect:/client/login";
            }
        }
        return "UserRegister";
    }

    //用户主页，返回容器，容器中包含了所有问卷信息，使用get请求。
    @GetMapping("/home/{username}")
    public String home(@PathVariable("username")String username, Model model){
        //根据用户名返回该用户所有问卷信息。
        model.addAttribute(userService.getQuestionnaire(username));
        return "UserQuestionnaireList";
    }

    //用户信息界面，返回该用户所有信息,使用get请求
    @GetMapping("/profile/message/{username}")
    public String  message(@PathVariable("username")String username, Model model){
        //通过用户名返回用户所有信息
        model.addAttribute(userService.findByUsername(username));
        return "UserProfile";
    }

    /**
     * 用户信息界面，修改信息，使用put请求
     */

    //传一个User对象回来,回传修改后的user对象

    @PutMapping("/update/user")
    public String updateUser(@RequestBody User User, Model model){
        model.addAttribute(userService.modify(User));
        return "UserProfile";
    }


    /**
     *新建问卷
     */
    //传一个问卷对象
//    @PostMapping("/create/{username}")
//    public String create(@RequestBody Questionnaire questionnaire,@PathVariable("username")String username){
//        boolean result=questionnaireService.add(questionnaire,username);
//        if(result) return "UserQuestionnaireList";
//        else return "UserQuestionnaireList";
//    }

    /**
     *修改问卷
     */
    //传修改后的问卷对象
    @PutMapping("/update/questionnaire")
    public String update(@RequestBody Questionnaire questionnaire, Model model){
        model.addAttribute(questionnaireService.modify(questionnaire));
        return "UserQuestionnaireList";
    }

    /**
     * 问卷信息界面
     */
    //get请求返回特定问卷的所有回答
    @GetMapping("/result/{id}")
    public String result(@PathVariable( "id") Integer id,Model model) {
        Questionnaire q=questionnaireService.findById(id);
        model.addAttribute(q);
        return "UserQuestionnaireList";
    }

    @GetMapping("/allSurvey")
    public String userSuervey(HttpServletRequest request, HttpServletResponse response, HttpSession session){
        //返回所有用户，用一个容器来存放，元素即为管理员对象
        String act1=request.getParameter("act1");
        String val=request.getParameter("userid");
        System.out.println(act1);
        System.out.println(val);
        if(act1.equals("load")) {
            try {
                request.setCharacterEncoding("UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            response.setContentType("text/json; charset=utf-8");
            PrintWriter out = null;
            try {
                out = response.getWriter();
            } catch (IOException e) {
                e.printStackTrace();
            }
            JSONArray jsonarray = new JSONArray();

            List<Questionnaire> questionnaires = questionnaireService.getQuestionnaires(1,10).getRecords();
            System.out.println(questionnaires);
            for (Questionnaire questionnaire : questionnaires) {
                if(questionnaire.getCreator().equals(session.getAttribute("username"))){
                    JSONObject jsonobj = new JSONObject();

                    jsonobj.put("id", questionnaire.getQuestionnaireId());
                    jsonobj.put("start", questionnaire.getStartTime());
                    jsonobj.put("end", questionnaire.getStartTime());
                    jsonobj.put("title", questionnaire.getTitle());
                    if (questionnaire.getStatus() == 0) {
                        jsonobj.put("status", "未审核");
                    } else if(questionnaire.getStatus() == 1) {
                        jsonobj.put("status", "审核通过");
                    } else if(questionnaire.getStatus() == 2){
                        jsonobj.put("status", "审核未通过");
                    }
                    jsonobj.put("questionCount",questionnaire.getQuestionCount());
                    jsonobj.put("link","http://localhost:8080/questionnaire/"+questionnaire.getQuestionnaireId());

                    jsonarray.add(jsonobj);
                }

            }
            try {
                out = response.getWriter();
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (out != null) {
                out.println(jsonarray);
            } else {
                System.out.println("空");
            }
            System.out.println(jsonarray);

        } else if(act1.equals("check")){
            Questionnaire questionnaire = questionnaireService.findById(Integer.parseInt(val));
            session.setAttribute("questionnaire", questionnaire);

            List<Question> questionList =questionnaireService.getQuestions(Integer.parseInt(val));
            session.setAttribute("questionList",questionList );
            List<Option> optionList = optionService.getOption(Integer.parseInt(val));

            session.setAttribute("optionList",optionList );
            return "UserFillIn";

        }else if(act1.equals("back")) {

            return "UserQuestionnaireList";
        }
        return null;

    }

    //新增问卷
    //新增问卷
    @GetMapping("/add")
    public String add(@RequestParam("questionnaire_id")String id,
                      @RequestParam("title")String title,
                      @RequestParam("start_time")@DateTimeFormat(iso = DateTimeFormat.ISO.DATE) Date start_time,
                      @RequestParam("end_time") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) Date end_time,
                      HttpServletRequest request) throws ParseException, ParseException {

        Questionnaire questionnaire = new Questionnaire();
        Questionnaire questionnaire1 = null;
        if (id != null && !id.equals("")) {
            questionnaire1 = questionnaireService.findById(Integer.parseInt(id));
        }

        if (Objects.equals(id, "")) {
            request.setAttribute("message", "id为空，请重新输入");
        } else if (questionnaire1 != null) {
            request.setAttribute("message", "该id已存在，请重新输入");
        } else if (Objects.equals(start_time, "")) {
            request.setAttribute("message", "起始时间为空，请重新输入");
        } else if (Objects.equals(end_time, "")) {
            request.setAttribute("message", "结束时间为空，请重新输入");
        } else if (Objects.equals(title, "")) {
            request.setAttribute("message", "问卷名称为空，请重新输入");
        } else {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            questionnaire.setQuestionnaireId(Integer.valueOf(id));
            questionnaire.setTitle(title);
            session.setAttribute("title", title);
            questionnaire.setStartTime(start_time);
            session.setAttribute("start_time", start_time);
            questionnaire.setEndTime(end_time);
            session.setAttribute("end_time", end_time);
            questionnaire.setCreator((String) session.getAttribute("username"));
            questionnaire.setManagerName("root");
            questionnaire.setQuestionCount(0);
            questionnaire.setStatus(0);
            questionnaireService.add(questionnaire);
        }
        return "UserQuestionnaireList";
    }

    //结果展示
    //结果展示
    @GetMapping("/show")
    public String show(@RequestParam("questionnaire_id")String id, HttpServletRequest request) {

        Questionnaire questionnaire1 = null;
        if (id != null && !id.equals("")) {
            questionnaire1 = questionnaireService.findById(Integer.parseInt(id));
        }

        if (Objects.equals(id, "")) {
            request.setAttribute("message", "id为空，请重新输入");
            return "UserQuestionnaireList";
        } else if (questionnaire1 == null) {
            request.setAttribute("message", "该id不存在，请重新输入");
            return "UserQuestionnaireList";
        } else {
            return "redirect:/questionnaire/"+id+"/show";
        }
    }
    //删除问卷
    @GetMapping("/delete")
    public String delete(@RequestParam("questionnaire_id")String id, HttpServletRequest request) {
        Questionnaire questionnaire1 = null;
        if (id != null && !id.equals("")) {
            questionnaire1 = questionnaireService.findById(Integer.parseInt(id));
        }

        if (Objects.equals(id, "")) {
            request.setAttribute("message", "id为空，请重新输入");
        } else if (questionnaire1 == null) {
            request.setAttribute("message", "该id不存在，请重新输入");
        } else {
            List<Question> questionList =  questionnaireService.getQuestions(Integer.parseInt(id));
            for(Question question:questionList){
                answerService.delete(question.getQuestionId());
                optionService.delete(question.getQuestionId());
            }
            questionService.delete(Integer.valueOf(id));
            questionnaireService.delete(Integer.valueOf(id));

            return "UserQuestionnaireList";
        }
        return "UserQuestionnaireList";
    }
    //删除问卷

    @PostMapping("/edit")
    public String edit(@RequestParam("questionnaire_id")String id, HttpServletRequest request) {

        Questionnaire questionnaire1 = null;
        if (id != null && !id.equals("")) {
            questionnaire1 = questionnaireService.findById(Integer.parseInt(id));
        }

        if (Objects.equals(id, "")) {
            request.setAttribute("message", "id为空，请重新输入");
            return "UserQuestionnaireList";
        } else if (questionnaire1 == null) {
            request.setAttribute("message", "该id不存在，请重新输入");
            return "UserQuestionnaireList";
        } else {
            session.setAttribute("id",id);
            System.out.println(session.getAttribute("id"));
        }
        return "redirect:/client/edit";
    }
    @RequestMapping("/question")
    @ResponseBody
    public String question(Integer question_num, String content, String type) throws InterruptedException {
//        Integer question_num = (Integer) params.get("question_num");
//        String content = (String) params.get("content");
//        String type = (String) params.get("type");
        System.out.println(question_num);
        System.out.println(content);
        System.out.println(type);
        Question question = new Question();
        question.setQuestionnaireId(Integer.valueOf((String) session.getAttribute("id")) );
        question.setQuestionNum(question_num);
        question.setContent(content);
        question.setType(type);
//        question.setQuestionId(questionId++);
        questionId++;
        System.out.println(questionService.count());
        List<Question> questions = questionService.getQuestions(Integer.valueOf((String) session.getAttribute("id")));
        Questionnaire questionnaire = questionnaireService.findById(Integer.valueOf((String) session.getAttribute("id")));
        questionService.add(question);
        questionnaire.setQuestionnaireId(Integer.valueOf((String) session.getAttribute("id")));
        questionnaire.setStartTime((Date) session.getAttribute("start_time"));
        questionnaire.setEndTime((Date) session.getAttribute("end_time"));
        questionnaire.setCreator((String) session.getAttribute("username"));
        questionnaire.setManagerName("root");
        questionnaire.setTitle((String) session.getAttribute("title"));
        questionnaire.setQuestionCount(questions.size()+1);
        questionnaire.setStatus(0);
        questionnaireService.modify(questionnaire);
        Thread.sleep(500);
        return "UserHome";
    }

    @RequestMapping("/question2")
    @ResponseBody
    public String question2(Integer option_num, String content) throws InterruptedException {
        Option option = new Option();
//        option.setId(optionId++);
        List<Question> questionList = questionService.getAllQuestions();
        int lastQuestionId = questionList.size();
        int lastQuestionId2 = questionList.get(lastQuestionId-1).getQuestionId();
        questionId = lastQuestionId2;
        option.setQuestionId(questionId);
        System.out.println(questionId);
        option.setQuestionnaireId(Integer.valueOf((String) session.getAttribute("id")));
        option.setOptionNum(option_num);
        option.setContent(content);
        optionService.add(option);
        Thread.sleep(500);
        return "UserHome";
    }

    @RequestMapping(value = "/update")
    public String update(HttpSession session, HttpServletRequest request) {
        String username = (String) session.getAttribute("username");
        User user = userService.findByUsername(username);

        if(!Objects.equals(request.getParameter("username"), "")) {
            user.setPhoneNum(request.getParameter("username"));
        }else {
            request.setAttribute("message", "用户名为空，请重新输入");
            System.out.println("用户名为空，请重新输入");
            return "UserProfile";
        }

        if(!Objects.equals(request.getParameter("phone"), "")) {
            user.setPhoneNum(request.getParameter("phone"));
        }else {
            request.setAttribute("message", "电话为空，请重新输入");
            System.out.println("电话为空，请重新输入");
            return "UserProfile";
        }

        if(!Objects.equals(request.getParameter("password"), "")) {
            user.setPassword(request.getParameter("password"));
        }else {
            request.setAttribute("message", "密码为空，请重新输入");
            System.out.println("密码为空，请重新输入");
            return "UserProfile";
        }
        session.setAttribute("user",userService.modify(user));
        return "UserProfile";
    }


    @RequestMapping("/edit")
    public String edit1(){
        return "CreateQuestionnaire";
    }

    @RequestMapping("/login")
    public String login1(){
        return "UserLogin";
    }

    @RequestMapping("/home")
    public String home(){
        return "UserHome";
    }

    @RequestMapping("/profile")
    public String profile(){
        return "UserProfile";
    }

    @RequestMapping("/questionnaireList")
    public String UserQuestionnaireList(){
        return "UserQuestionnaireList";
    }

    @RequestMapping("/register")
    public String register(){
        return "UserRegister";
    }


}
